package com.kangjia.model.m0.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.kangjia.api.ReportApiImpl;
import com.kangjia.general.dao.query.OperType;
import com.kangjia.general.dao.query.Page;
import com.kangjia.general.dao.query.Param;
import com.kangjia.general.dao.query.QueryParam;
import com.kangjia.general.dao.query.order.Order;
import com.kangjia.general.dao.query.order.OrderType;
import com.kangjia.holder.TableContextHolder;
import com.kangjia.holder.VariableThreadLocal;
import com.kangjia.jasckson.DataMapper;
import com.kangjia.model.m0.entity.Employee;
import com.kangjia.model.m0.entity.StoreReport;
import com.kangjia.model.m0.entity.ViewStoreReport;
import com.kangjia.model.m0.service.ParseService;
import com.kangjia.model.m0.service.ReportService;
import com.kangjia.response.AbstractResponse;
import com.kangjia.response.ErrorResponse;
import com.kangjia.response.PageResponse;
import com.kangjia.response.SuccessResponse;
import com.kangjia.util.JsonNodeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
@RequestMapping(value = "/b/report", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ReportController {

	@Autowired
	private ReportService reportService;
	@Autowired
	private ReportApiImpl reportApiImpl;
	@Autowired
	private JedisPool jedisPool;
	@Value("${report.dir}")
	private String dir;
	@Autowired
	private ParseService parseService;
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@RequestMapping(value = "/editor")
	@ResponseBody
	public AbstractResponse editor(@RequestBody Report report) {
		reportService.update(report);
		return new SuccessResponse("操作成功");
	}

	@RequestMapping(value = "/bind")
	@ResponseBody
	public AbstractResponse bind(@RequestBody Report report) {
		Jedis jedis = jedisPool.getResource();
		try {
			String json = jedis.hget("device", report.getSn());
			JsonNode jsonNode = DataMapper.getInstance().readTree(json);
			Integer storeId = JsonNodeUtil.integer(jsonNode, "storeId");
			reportService.bind(report.getSn(), storeId);
		} catch (Exception e) {

		} finally {
			jedis.close();
		}
		return new SuccessResponse("操作成功");
	}

	@RequestMapping(value = "/search")
	@ResponseBody
	public PageResponse<StoreReport> query(@RequestBody Report report) {
		Page page = new Page();
		page.setStart(report.getStart());
		page.setLimit(report.getLimit());
		QueryParam param = createParam(report, page);
		List<StoreReport> list = reportService.pager(StoreReport.class, param);
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (StoreReport sr : list) {
			Integer storeId = sr.getStorePk().getStoreId();
			sr.setInspectId(sr.getStorePk().getInspectId());
			cal.setTimeInMillis(sr.getCrtime());
			sr.setDateTime(sdf.format(cal.getTime()));
			sr.setStoreId(sr.getStorePk().getStoreId());
			String json = reportApiImpl.get("store", String.valueOf(storeId));
			if (StringUtils.isNotBlank(json)) {
				try {
					JsonNode jsonNode = DataMapper.getInstance().readTree(json);
					sr.setStoreName(JsonNodeUtil.string(jsonNode, "cname"));
					sr.setStoreId(sr.getStorePk().getStoreId());
				} catch (JsonProcessingException e) {

				} catch (IOException e) {

				}
			}
			Employee e = reportService.getEmployee(sr.getInspectId());
			if (e != null) {
				sr.setEmployeeName(e.getEmployeeName());
			}
		}
		return new PageResponse<>(param != null ? param.getTotal() : null, list);
	}
	
	/**
	 * 查询条件
	 * @param report
	 * @param page
	 * @return
	 */
	private QueryParam createParam(Report report, Page page) {
		QueryParam param = new QueryParam(page);
		JsonNode jn = VariableThreadLocal.get("login");
		Integer busId = JsonNodeUtil.integer(jn, "busId");
		if (busId.equals(2)) {
			TableContextHolder.mod(TableContextHolder.store, -1L, 10L);
			if (report.getStoreId() != null) {
				TableContextHolder.mod(TableContextHolder.store, new Long(report.getStoreId()), 10L);
				param.addParam(new Param<Integer>("storePk.storeId", OperType.eq, report.getStoreId()));
			}
		} else {
			TableContextHolder.mod(TableContextHolder.store, new Long(JsonNodeUtil.integer(jn, "storeId")), 10L);
			param.addParam(new Param<Integer>("storePk.storeId", OperType.eq, JsonNodeUtil.integer(jn, "storeId")));
		}
		if (StringUtils.isNotBlank(report.getMobile())) {
			param.addParam(new Param<String>("mobile", OperType.eq, report.getMobile()));
		}
		if (StringUtils.isNotBlank(report.getName())) {
			param.addParam(new Param<String>("name", OperType.eq, report.getName()));
		}
		if (StringUtils.isNotBlank(report.getSn())) {
			param.addParam(new Param<String>("sn", OperType.eq, report.getSn()));
		}
		if (StringUtils.isNotBlank(report.getStartDate())) {
			param.addParam(new Param<Long>("crtime", OperType.ge, getTime(report.getStartDate() + " 00:00:00")));
		}
		if (StringUtils.isNotBlank(report.getEndDate())) {
			param.addParam(new Param<Long>("crtime", OperType.le, getTime(report.getEndDate() + " 23:59:59")));
		}
		param.addOrder(new Order("crtime", OrderType.DESC));
		return param;
	}
	
	public long getTime(String d) {
		try {
			return sdf.parse(d).getTime();
		} catch (ParseException e) {
			return 0L;
		}
	}

	@RequestMapping(value = "/pringReport")
	@ResponseBody
	public AbstractResponse create(@RequestBody Report report) {
		Jedis jedis = jedisPool.getResource();
		Integer storeId = report.getStoreId();
		try {
			String store = jedis.hget("store", storeId.toString());
			String name = "";
			if (StringUtils.isNoneBlank(store)) {
				JsonNode storeNode = DataMapper.getInstance().readTree(store);
				name = storeNode.get("cname").asText();
			}
			String uuid = UUID.randomUUID().toString();
			jedis.hset(uuid, "inspectId", report.getInspectId());
			jedis.hset(uuid, "name", name);
			jedis.expire(uuid, 600);
			return new SuccessResponse(uuid);
		} catch (Exception e) {
			return new ErrorResponse("生成失败");
		} finally {
			jedis.close();
		}
	}

	@RequestMapping(value = "/destory")
	@ResponseBody
	public AbstractResponse destory() {
		parseService.clear();
		return new SuccessResponse("销毁内存数据");
	}
	
	@RequestMapping(value = "/export")
	@ResponseBody
	public AbstractResponse export(@RequestBody Report report) {
		QueryParam param = createParam(report, null);
		String key = UUID.randomUUID().toString();
		PringController.params.put(key, param);
		JsonNode jn = VariableThreadLocal.get("login");
		Integer busId = JsonNodeUtil.integer(jn, "busId");
		if (busId.equals(2)) {
			PringController.mods.put(key, -1);
			if (report.getStoreId() != null) {
				PringController.mods.put(key, report.getStoreId());
			}
		} else {
			PringController.mods.put(key, JsonNodeUtil.integer(jn, "storeId"));
		}
		return new SuccessResponse(key);
	}
	
	@RequestMapping(value = "/full/export")
	@ResponseBody
	public AbstractResponse fullExport(@RequestBody Report report) {
		QueryParam param = createParamReport(report, null);
		String key = UUID.randomUUID().toString();
		PringController.params.put(key, param);
		return new SuccessResponse(key);
	}
	
	@RequestMapping(value = "/full")
	@ResponseBody
	public PageResponse<ViewStoreReport> full(@RequestBody Report report) {
		Page page = new Page();
		page.setStart(report.getStart());
		page.setLimit(report.getLimit());
		QueryParam param = createParamReport(report, page);
		List<ViewStoreReport> list = reportService.pager(ViewStoreReport.class, param);
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (ViewStoreReport sr : list) {
			Integer storeId = sr.getStoreId();
			cal.setTimeInMillis(sr.getCrtime());
			sr.setDateTime(sdf.format(cal.getTime()));
			String json = reportApiImpl.get("store", String.valueOf(storeId));
			if (StringUtils.isNotBlank(json)) {
				try {
					JsonNode jsonNode = DataMapper.getInstance().readTree(json);
					sr.setStoreName(JsonNodeUtil.string(jsonNode, "cname"));
				} catch (JsonProcessingException e) {

				} catch (IOException e) {

				}
			}
			Employee e = reportService.getEmployee(sr.getInspectId());
			if (e != null) {
				sr.setEmployeeName(e.getEmployeeName());
			}
		}
		return new PageResponse<>(param != null ? param.getTotal() : null, list);
	}
	
	/**
	 * 查询条件
	 * @param report
	 * @param page
	 * @return
	 */
	private QueryParam createParamReport(Report report, Page page) {
		QueryParam param = new QueryParam(page);
		if (report.getStoreId() != null) {
			param.addParam(new Param<Integer>("storeId", OperType.eq, report.getStoreId()));
		}
		if (StringUtils.isNotBlank(report.getMobile())) {
			param.addParam(new Param<String>("mobile", OperType.eq, report.getMobile()));
		}
		if (StringUtils.isNotBlank(report.getName())) {
			param.addParam(new Param<String>("name", OperType.eq, report.getName()));
		}
		if (StringUtils.isNotBlank(report.getSn())) {
			param.addParam(new Param<String>("sn", OperType.eq, report.getSn()));
		}
		if (StringUtils.isNotBlank(report.getStartDate())) {
			param.addParam(new Param<Long>("crtime", OperType.ge, getTime(report.getStartDate() + " 00:00:00")));
		}
		if (StringUtils.isNotBlank(report.getEndDate())) {
			param.addParam(new Param<Long>("crtime", OperType.le, getTime(report.getEndDate() + " 23:59:59")));
		}
		param.addOrder(new Order("crtime", OrderType.DESC));
		return param;
	}
}
